//
//  PictureWaterModule.m
//  DCNativeApiPlugin
//
//  Created by iOSTean on 2022/6/7.
//
#import "PictureWaterModule.h"
#import "UIImage+Water.h"
#import "PDRCoreApp.h"
#import "PDRCoreAppManager.h"
#import "PDRCoreAppInfo.h"
#import "WaterUtils.h"
#define kScreenWidth    [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight   [[UIScreen mainScreen] bounds].size.height
#define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
/**
 * 格式化字符串
 */
#define FORMAT(fmt, ...) [NSString stringWithFormat:(fmt), ##__VA_ARGS__]
typedef NS_ENUM(NSInteger,WaterType) {
    WaterTypeLeftBottom,//左下角加水印
    WaterTypeRightBottom,//右下角加水印
    WaterTypeLeftTop,//左上角加水印
    WaterTypeRightTop,//右上角加水印
};
typedef NS_ENUM(NSInteger,IconType) {
    IconTypeNone=0,//无修饰 默认
    IconTypePoint,//圆圈 仅在左边有效
    IconTypeIcon//图标
};
@interface PictureWaterModule()
/// 图片压缩大小 默认0.5
@property(nonatomic,assign)CGFloat compressSize;
/// 水印类型
@property(nonatomic,assign)WaterType waterType;
/// 修饰类型
@property(nonatomic,assign)IconType iconType;
/// 当前时间戳
@property(nonatomic,strong)NSString *currentTimeTem;
/// 水平水印是否显示图标
@property(nonatomic,assign)BOOL showHorizontalIcon;
///水印时间
@property(nonatomic,strong)NSString *timeStr;
///返回图片路径 默认不返回
@property(nonatomic,assign)BOOL outPath;
///字体大小
@property(nonatomic,assign)CGFloat fontSize;
/// 文字颜色
@property(nonatomic,strong)UIColor *textColor;
@property(nonatomic,strong)NSString *textColorStr;
///斜体自定义文案
@property(nonatomic,strong)NSString *customText;
@property(nonatomic,assign)BOOL rotateWater;
/// 顶部偏移
@property(nonatomic,assign)NSInteger upY;
/// 底部偏移
@property(nonatomic,assign)NSInteger dwonY;
@end
@implementation PictureWaterModule
- (void)configPamars:(NSDictionary *)pictureData{
    self.textColor = UIColor.whiteColor;
    self.textColorStr = @"#ffffff";
    self.iconType = IconTypeNone;
    self.fontSize = 15.0f;
    self.customText = [self currentDateStr];;
    self.compressSize = 1;
    self.currentTimeTem = [self currentTimeStr];
    self.waterType = WaterTypeLeftBottom;
    self.rotateWater = NO;
    self.upY = 50;
    self.dwonY = 20;
    if ([pictureData.allKeys containsObject:@"outputPath"] && [[pictureData valueForKey:@"outputPath"] boolValue]) {
        self.outPath = YES;
    }
    if([pictureData.allKeys containsObject:@"rotateWater"] && [[pictureData valueForKey:@"rotateWater"] boolValue]){
        self.rotateWater = YES;
    }
    if ([pictureData.allKeys containsObject:@"compressSize"] && [[pictureData valueForKey:@"compressSize"] floatValue]>0) {
        self.compressSize = [[pictureData valueForKey:@"compressSize"] floatValue];
    }
    if (!kStringIsEmpty([pictureData valueForKey:@"waterType"])) {
        if ([[pictureData valueForKey:@"waterType"] isEqualToString:@"leftBottom"]) {
            self.waterType = WaterTypeLeftBottom;
        }
        if ([[pictureData valueForKey:@"waterType"] isEqualToString:@"leftTop"]) {
            self.waterType = WaterTypeLeftTop;
        }
        if ([[pictureData valueForKey:@"waterType"] isEqualToString:@"rightTop"]) {
            self.waterType = WaterTypeRightTop;
        }
        if ([[pictureData valueForKey:@"waterType"] isEqualToString:@"rightBottom"]) {
            self.waterType = WaterTypeRightBottom;
        }
    }
    
//    样式
    if ([pictureData valueForKey:@"configStyle"]) {
        NSDictionary *styleDict = [pictureData valueForKey:@"configStyle"];
//        字体大小
        if([styleDict.allKeys containsObject:@"fontSize"]&&[[styleDict valueForKey:@"fontSize"] floatValue]>0){
            self.fontSize = [[styleDict valueForKey:@"fontSize"] floatValue];
        }
//        字体颜色
        if([styleDict.allKeys containsObject:@"textColor"] && !kStringIsEmpty([styleDict valueForKey:@"textColor"])){
            self.textColor = [WaterUtils sd_colorWithHexString:[styleDict valueForKey:@"textColor"] alpha:1];
            self.textColorStr = [styleDict valueForKey:@"textColor"];
        }
//        装饰
        if ([styleDict.allKeys containsObject:@"decorate"] && !kStringIsEmpty([styleDict valueForKey:@"decorate"])) {
            NSString *decorateStr = [styleDict valueForKey:@"decorate"];
            if([decorateStr containsString:@"point"]){
                self.iconType = IconTypePoint;
            }
            if([decorateStr containsString:@"icon"]){
                self.iconType = IconTypeIcon;
            }
        }
        //    上下偏移
        if([styleDict.allKeys containsObject:@"topY"] && [[styleDict valueForKey:@"topY"] floatValue]>0){
            self.upY = [[styleDict valueForKey:@"topY"] floatValue];
        }
        if([styleDict.allKeys containsObject:@"bottomY"] && [[styleDict valueForKey:@"bottomY"] floatValue]>0){
            self.dwonY = [[styleDict valueForKey:@"bottomY"] floatValue];
        }
    }
//    斜体自定义文案
    if([pictureData valueForKey:@"RotateCustomText"] && !kStringIsEmpty([pictureData valueForKey:@"RotateCustomText"])){
        self.customText = [pictureData valueForKey:@"RotateCustomText"];
    }
//    self.waterType = WaterTypeLeftTop;
//    self.iconType = IconTypeIcon;
}
UNI_EXPORT_METHOD(@selector(addWaterForBase64:callBack:))
- (void)addWaterForBase64:(NSDictionary *)pictureData callBack:(UniModuleKeepAliveCallback)callback{
    [self configPamars:pictureData];
    if ([[pictureData allKeys] containsObject:@"photos"]) {
        NSArray *paths = pictureData[@"photos"];
        NSString *prefixStr = @"data:image/jpeg;base64,";
        NSMutableArray *pothos = [[NSMutableArray alloc] init];
        
        [paths enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *pothoStr =obj[@"path"];
            if([pothoStr containsString:@","]){
                pothoStr = [pothoStr componentsSeparatedByString:@","][1];
            }
            NSData * showData = [[NSData alloc]initWithBase64EncodedString:pothoStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
            UIImage *image = [UIImage imageWithData:showData];
            if (!image) {
                NSURL *photoUrl = [NSURL URLWithString:pothoStr];
                showData = [NSData dataWithContentsOfURL:photoUrl];
                image = [UIImage imageWithData:showData];
            }
            NSArray *contens = obj[@"contents"];
            @autoreleasepool {
                UIImage *drawImage =nil;
                if(self.rotateWater){
                    NSDictionary *dict = [self ly_rotationWaterContents:contens];
                    UIImage *ratateImage = [image ly_addWatermarkWithWatermarkImages:nil watermarkContents:dict];
                    drawImage = [self addWatermarkForImage:ratateImage waterType:self.waterType contens:contens];
                }else{
                    drawImage = [self addWatermarkForImage:image waterType:self.waterType contens:contens];
                }
               
                NSData * imageData = [self compressOriginalImage:drawImage toMaxDataSizeMBytes:self.compressSize];

                NSString * base64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                NSString *resultString = [NSString stringWithFormat:@"%@%@",prefixStr,base64Str];
                NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
                [resultDict setValue:resultString forKey:@"base64"];
                [resultDict setValue:@"" forKey:@"path"];
                if(self.outPath){
                    PDRCoreAppInfo *appinfo = [PDRCore Instance].appManager.getMainAppInfo;
                    NSString *fullPath = [appinfo.documentPath stringByAppendingPathComponent:FORMAT(@"%@%ld.jpg",self.currentTimeTem,idx)];
                    BOOL b = [imageData writeToFile:fullPath atomically:NO];
                    if(b){
                        [resultDict setValue:FORMAT(@"_doc/%@%ld.jpg",self.currentTimeTem,idx) forKey:@"path"];
                    }
                }
                [pothos addObject:resultDict];
            }
        }];
        if (callback) {
            callback(pothos, YES);
        }
    }
}
UNI_EXPORT_METHOD(@selector(addWaterForPath:callBack:))
-(void)addWaterForPath:(NSDictionary *)pictureData callBack:(UniModuleKeepAliveCallback)callback{
//    NSLog(@"%@",pictureData);
    [self configPamars:pictureData];
    if ([[pictureData allKeys] containsObject:@"photos"]) {
        NSString *prefixStr = @"data:image/jpeg;base64,";
        NSArray *paths = pictureData[@"photos"];
        NSMutableArray *pothos = [[NSMutableArray alloc] init];
        PDRCoreAppInfo *appinfo = [PDRCore Instance].appManager.getMainAppInfo;
        [paths enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableString *pothoStr = [NSMutableString stringWithString:obj[@"path"]];
            if([pothoStr hasPrefix:@"_doc"]){//以_doc开头 相机
                [pothoStr replaceCharactersInRange:NSMakeRange(0, @"_doc".length) withString:appinfo.documentPath];
            }
            NSData *showData = [NSData dataWithContentsOfFile:pothoStr];
            UIImage *image = [UIImage imageWithData:showData];
            if (!image) {
                NSURL *photoUrl = [NSURL URLWithString:pothoStr];
                showData = [NSData dataWithContentsOfURL:photoUrl];
                image = [UIImage imageWithData:showData];
            }
            NSArray *contens = obj[@"contents"];
            @autoreleasepool {
                UIImage *drawImage =nil;
                if(self.rotateWater){
                    NSDictionary *dict = [self ly_rotationWaterContents:contens];
                    UIImage *ratateImage = [image ly_addWatermarkWithWatermarkImages:nil watermarkContents:dict];
                    drawImage = [self addWatermarkForImage:ratateImage waterType:self.waterType contens:contens];
                }else{
                    drawImage = [self addWatermarkForImage:image waterType:self.waterType contens:contens];
                }
               
                NSData * imageData = [self compressOriginalImage:drawImage toMaxDataSizeMBytes:self.compressSize];
                NSString * base64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                NSString *resultString = [NSString stringWithFormat:@"%@%@",prefixStr,base64Str];
                NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
                [resultDict setValue:resultString forKey:@"base64"];
                [resultDict setValue:@"" forKey:@"path"];
                if(self.outPath){
                    NSString *fullPath = [appinfo.documentPath stringByAppendingPathComponent:FORMAT(@"%@%ld.jpg",self.currentTimeTem,idx)];
                   BOOL b = [imageData writeToFile:fullPath atomically:NO];
                    if(b){
                        [resultDict setValue:FORMAT(@"_doc/%@%ld.jpg",self.currentTimeTem,idx) forKey:@"path"];
                    }
                }
                [pothos addObject:resultDict];
            }
        }];
        if (callback) {
            callback(pothos, YES);
        }
    }
    
}
UNI_EXPORT_METHOD_SYNC(@selector(clearCacheWithFilePath:))
-(BOOL)clearCacheWithFilePath:(NSString *)path{
    return [WaterUtils clearCacheWithFilePath:path];
}
//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}
- (NSString *)currentDateStr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *time = [dateFormatter stringFromDate:NSDate.date];
    return time;
}
#pragma mark 获取斜体水印文案
- (NSDictionary *)ly_rotationWaterContents:(NSArray *)arr{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:self.customText forKey:@"rotateText"];
    [dict setValue:@(self.fontSize) forKey:@"fontSize"];
    [dict setValue:self.textColorStr forKey:@"color"];
    [dict setValue:@(self.iconType) forKey:@"iconType"];
    if(arr){
        [dict setValue:arr forKey:@"contents"];
    }
    return dict;
}
#pragma mark 压缩图片至指定大小
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeMBytes:(CGFloat)quality {
    // 压缩图片尺寸
    UIImage *resizeImage = [self wxImageSize:image];
    // 压缩图片质量
    CGFloat compression = 1.0f;
    NSData *data = UIImageJPEGRepresentation(resizeImage, compression);
    CGFloat real = data.length / 1000.f / 1000.f;
    if (0 < quality && real < quality) return data;
    // 二分法优化   (压缩 6 次, 1/(2^6) = 0.015625, 满足实际需求)
    CGFloat max = 1.f;
    CGFloat min = 0.f;
    for (int i = 0; i < 6; i++) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(resizeImage, compression);
        real = data.length / 1000.f / 1000.f;
        
        if (real < quality * 0.9) {
            min = compression;
        } else if (real > quality) {
            max = compression;
        } else {
            break;
        }
    }
    
    return data;
}
#pragma mark 仿微信压缩图片尺寸
- (UIImage *)wxImageSize:(UIImage *)image {
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    CGFloat boundary = 1280;
    // width, height <= 1280, Size remains the same
    if (imageWidth <= boundary && imageHeight <= boundary) {
        UIImage *newImage = [UIImage newImageWithImage:image scaledToSize:CGSizeMake(imageWidth, imageHeight)];
        return newImage;
    }

    // aspect ratio
    CGFloat s = MAX(imageWidth, imageHeight) / MIN(imageWidth, imageHeight);
    if (s <= 2) {
        // Set the larger value to the boundary, the smaller the value of the compression
        CGFloat x = MAX(imageWidth, imageHeight) / boundary;
        if (imageWidth > imageHeight) {
            imageWidth = boundary ;
            imageHeight = imageHeight / x;
        } else {
            imageHeight = boundary;
            imageWidth = imageWidth / x;
        }
    } else {
        if (MIN(imageWidth, imageHeight) >= boundary) {
            //- parameter type: session image boundary is 800, timeline is 1280
            // boundary = type == .session ? 800 : 1280
            CGFloat x = MIN(imageWidth, imageHeight) / boundary;
            if (imageWidth < imageHeight) {
                imageWidth = boundary;
                imageHeight = imageHeight / x;
            } else {
                imageHeight = boundary;
                imageWidth = imageWidth / x;
            }
        }
    }
    UIImage *newImage = [UIImage newImageWithImage:image scaledToSize:CGSizeMake(imageWidth, imageHeight)];
    return newImage;
}
#pragma mark 添加水印
- (UIImage *)addWatermarkForImage:(UIImage *)image waterType:(WaterType)type contens:(NSArray *)contents{
    CGFloat widthScale = image.size.width / kScreenWidth * 1.f;
    CGFloat heightScale = image.size.height / kScreenHeight * 1.f;
    CGFloat iconWidth = 18.0f * widthScale;
    CGFloat interval = 4.f * heightScale;
    CGFloat ori_X = 15.f * widthScale;
    //                设置初始下方y坐标
    CGFloat bottomY = image.size.height - self.dwonY * heightScale;
    CGFloat topY    = self.upY*heightScale;
    UIFont *font = [UIFont fontWithName:@"Arial" size:self.fontSize * widthScale];
    NSDictionary *dictionary = @{NSForegroundColorAttributeName:self.textColor, NSFontAttributeName:font};
    UIGraphicsBeginImageContext(image.size);
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    for ( int i=0; i<contents.count; i++) {
        NSDictionary *contentDict = contents[i];
        NSString *mes = [contentDict valueForKey:@"text"];
        if(self.iconType == IconTypePoint){
            mes = FORMAT(@"• %@",mes);
        }
        switch (type) {
            case WaterTypeRightBottom:{//右下
                CGFloat width = [WaterUtils stringWidth:mes withFont:font];
                width = width>image.size.width-2.0f*ori_X?image.size.width-2.0f*ori_X:width;
                CGFloat height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:image.size.width-2.0f*ori_X];
                CGRect textRect;
                  if(self.iconType == IconTypeIcon){
                      width = width>image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale?image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale:width;
                      height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale];
                      bottomY = bottomY-height-2.0*interval;
                      UIImage *locationImage = [WaterUtils converUniPath:[contentDict valueForKey:@"icon"]];
                      textRect = CGRectMake(image.size.width-ori_X-width,bottomY,width,height);
                      CGRect iconRect = CGRectMake(textRect.origin.x-iconWidth-5.f*widthScale,bottomY,iconWidth,iconWidth);
                      [locationImage drawInRect:iconRect withContentMode:(UIViewContentModeScaleAspectFit) clipsToBounds:YES];
                  }else{
                      bottomY = bottomY-height-interval;
                      textRect = CGRectMake(image.size.width-ori_X-width,bottomY,width,height);
                  }
                  [mes drawInRect:textRect withAttributes:dictionary];
            }
                break;
            case WaterTypeLeftTop:{//左上
                //               计算文字宽高
                CGFloat width = [WaterUtils stringWidth:mes withFont:font];
                width = width>image.size.width-2.0f*ori_X?image.size.width-2.0f*ori_X:width;
                CGFloat height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:image.size.width-2.0f*ori_X];
                CGRect textRect;
                if(self.iconType == IconTypeIcon){
                    width = width>image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale?image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale:width;
                    height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:width];
                    textRect = CGRectMake(ori_X+iconWidth+5.f*widthScale,topY,width,height);
                    UIImage *locationImage = [WaterUtils converUniPath:[contentDict valueForKey:@"icon"]];
                    CGRect iconRect = CGRectMake(ori_X,topY,iconWidth,iconWidth);
                    [locationImage drawInRect:iconRect withContentMode:(UIViewContentModeScaleAspectFit) clipsToBounds:YES];
                    topY = topY+height+2.0*interval;
                }else{
                    topY = topY+height+interval;
                    textRect = CGRectMake(ori_X,topY,width,height);
                }
                [mes drawInRect:textRect withAttributes:dictionary];
            }
                break;
            case WaterTypeRightTop:{//右上
                CGFloat width = [WaterUtils stringWidth:mes withFont:font];
                width = width>image.size.width-2.0f*ori_X?image.size.width-2.0f*ori_X:width;
                CGFloat height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:image.size.width-2.0f*ori_X];
                CGRect textRect;
                if(self.iconType == IconTypeIcon){
                    width = width>image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale?image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale:width;
                    height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:width];
                    textRect = CGRectMake(image.size.width-ori_X-width,topY,width,height);
                    UIImage *locationImage = [WaterUtils converUniPath:[contentDict valueForKey:@"icon"]];
                    CGRect iconRect = CGRectMake(textRect.origin.x-iconWidth-5.f*widthScale,topY,iconWidth,iconWidth);
                    [locationImage drawInRect:iconRect withContentMode:(UIViewContentModeScaleAspectFit) clipsToBounds:YES];
                    topY = topY+height+2.0*interval;
                }else{
                    topY = topY+height+interval;
                    textRect = CGRectMake(image.size.width-ori_X-width,topY,width,height);
                }
                [mes drawInRect:textRect withAttributes:dictionary];
            }
                break;
            default:{//左下
//               计算文字宽高
              CGFloat width = [WaterUtils stringWidth:mes withFont:font];
              width = width>image.size.width-2.0f*ori_X?image.size.width-2.0f*ori_X:width;
              CGFloat height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:image.size.width-2.0f*ori_X];
              CGRect textRect;
                if(self.iconType == IconTypeIcon){
                    width = width>image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale?image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale:width;
                    height = [WaterUtils stringHeightWithString:mes stringFont:font textWidth:image.size.width-2.0f*ori_X-iconWidth-5.f*widthScale];
                    bottomY = bottomY-height-2.0*interval;
                    UIImage *locationImage = [WaterUtils converUniPath:[contentDict valueForKey:@"icon"]];
                    CGRect iconRect = CGRectMake(ori_X,bottomY,iconWidth,iconWidth);
                    textRect = CGRectMake(ori_X+iconWidth+5.f*widthScale,bottomY,width,height);
                    [locationImage drawInRect:iconRect withContentMode:(UIViewContentModeScaleAspectFit) clipsToBounds:YES];
                }else{
                    bottomY = bottomY-height-interval;
                    textRect = CGRectMake(ori_X,bottomY,width,height);
                }
                [mes drawInRect:textRect withAttributes:dictionary];
            }
                break;
        }
    }
    UIImage *watermarkImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return watermarkImage;
}
/// 获取文件大小
/// //路径
UNI_EXPORT_METHOD(@selector(sizeAtPath:))
- (unsigned long long)sizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    NSMutableString *pothoStr = [NSMutableString stringWithString:filePath];
    if([pothoStr hasPrefix:@"_doc"]){//以_doc开头 相机
        PDRCoreAppInfo *appinfo = [PDRCore Instance].appManager.getMainAppInfo;
        [pothoStr replaceCharactersInRange:NSMakeRange(0, @"_doc".length) withString:appinfo.documentPath];
    }
    if ([manager fileExistsAtPath:pothoStr]){
        return [[manager attributesOfItemAtPath:pothoStr error:nil] fileSize];
    }
    return 0;
}

@end
